//
//  AccountViewController.m
//  MarryMe
//
//  Created by lanou3g on 16/1/14.
//  Copyright © 2016年 revocher. All rights reserved.
//

#import "AccountViewController.h"
#import "AccoutTextViewController.h"
#import "AccountCollectionViewCell.h"
#import "AcoutLiftCollectionViewCell.h"
#import "Mothy.h"
#import "ModifyViewController.h"
#import "CoreDataHandle.h"

#define Width  [UIScreen mainScreen].bounds.size.width
@interface AccountViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) IBOutlet UIImageView *tapimageView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) IBOutlet UILabel *liftLable;
@property (strong, nonatomic) IBOutlet UILabel *rightLable;
@property(strong,nonatomic)UIView *contview;
@property(strong,nonatomic)UIButton *rightButton;
@property(strong,nonatomic)UIButton *liftButton;
@property(strong,nonatomic)UIImageView *topImageView;
@property(nonatomic,strong)UILabel *label;
@property(nonatomic,strong)NSMutableArray *array;
@end

@implementation AccountViewController
//视图出现获取数据刷新
-(void)viewWillAppear:(BOOL)animated{
    [[CoreDataHandle shareCoreDataHandle]getCoreData];
    NSFetchRequest *request=[[NSFetchRequest alloc]initWithEntityName:@"Mothy"];
    NSArray *objcArray=[[CoreDataHandle shareCoreDataHandle].context executeFetchRequest:request error:nil];
    self.array=[NSMutableArray array];
    self.array=[NSMutableArray arrayWithArray:objcArray];
    //将数组倒序
    self.array = (NSMutableArray *)[[self.array reverseObjectEnumerator] allObjects];
    int sum=0;
    int num=0;
    for (Mothy *moth in self.array) {
        if ([moth.picture isEqualToString:@"type_big_24"]) {
            
            int a=[moth.closed intValue];
            sum+=a;
        self.rightLable.text=[NSString stringWithFormat:@"%d",sum];
        }else{
            int b=[moth.closed intValue];
            num+=b;
        
            self.liftLable.text=[NSString stringWithFormat:@"%d",num];
        }
    }
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"礼金记账";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    UITapGestureRecognizer *taypGR=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGRAction:)];
    [self.tapimageView addGestureRecognizer:taypGR];
    self.tapimageView.userInteractionEnabled=YES;
    //设置代理
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
}

-(void)deleteAction:(UIButton*)sender{
      [[NSNotificationCenter defaultCenter]postNotificationName:@"name" object:nil];
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"您确定要删除此信息" preferredStyle: UIAlertControllerStyleAlert];
    UIAlertAction *action1=[UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIView *v = [sender superview];//获取父类view
        UICollectionViewCell *cell =(UICollectionViewCell*)[v superview];//获取cell
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];//获取cell对应的indexpath;
        NSLog(@"%@",indexPath);
        Mothy *acodate=self.array[indexPath.row];
        if (self.array.count>0) {
            NSMutableArray *temp=[NSMutableArray arrayWithArray:self.array];
            [temp removeObjectAtIndex:indexPath.item];
            self.array=temp;
            [self.collectionView performBatchUpdates:^{
                [self.collectionView  deleteItemsAtIndexPaths:@[indexPath]];
            } completion:nil];
        [self.collectionView reloadData];
        
        }else{
            [self.array removeAllObjects];
            [self.collectionView reloadData];
        }
     
        int su=0;
        for (Mothy *moth in self.array) {
            if ([moth.picture isEqualToString:@"type_big_24"]) {
            int a=[moth.closed intValue];
                 NSLog(@"++++++++%d",a);
            su+=a;
              
            self.rightLable.text=[NSString stringWithFormat:@"%d",su];
            }
        }

        //删除Codata数据库的的某一类对象必须遍历
        NSFetchRequest *request=[[NSFetchRequest alloc]initWithEntityName:@"Mothy"];
        NSArray *array=[[CoreDataHandle shareCoreDataHandle].context executeFetchRequest:request error:nil];
        if (array.count>0) {
            for (Mothy *a in array) {
                if ([a.name isEqualToString:acodate.name]) {
                    [[CoreDataHandle shareCoreDataHandle].context deleteObject:a];
                }
            }
            if ([[CoreDataHandle shareCoreDataHandle].context hasChanges]) {
                [[CoreDataHandle shareCoreDataHandle].context save:nil];
            }
            
        }
    
            } ];
    UIAlertAction *acetion2=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:acetion2];
    [self presentViewController:alert animated:YES completion:nil];

}
-(void)editButtonAction:(UIButton*)sender{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"name" object:nil];
    UIView *v = [sender superview];//获取父类view
    UICollectionViewCell *cell =(UICollectionViewCell*)[v superview];//获取cell
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];//获取cell对应的indexpath;
    ModifyViewController *modifyVC=[[ModifyViewController alloc]init];
    modifyVC.modle=self.array[indexPath.row];

    UINavigationController *modifyNC=[[UINavigationController alloc]initWithRootViewController:modifyVC];
    [self presentViewController:modifyNC animated:YES completion:nil];
    
}
-(void)deleteButtonAction:(UIButton*)sender{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"name" object:nil];
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"您确定要删除此信息" preferredStyle: UIAlertControllerStyleAlert];
    UIAlertAction *action1=[UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIView *v = [sender superview];//获取父类view
        UICollectionViewCell *cell =(UICollectionViewCell*)[v superview];//获取cell
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];//获取cell对应的indexpath;
        Mothy *acodate=self.array[indexPath.row];
        if (self.array.count>0) {
            NSMutableArray *temp=[NSMutableArray arrayWithArray:self.array];
            [temp removeObjectAtIndex:indexPath.item];
            self.array=temp;
            [self.collectionView performBatchUpdates:^{
                [self.collectionView  deleteItemsAtIndexPaths:@[indexPath]];
            } completion:nil];
           
            [self.collectionView reloadData];
        
        }else{
            [self.array removeAllObjects];
            [self.collectionView reloadData];
        }
        int nu=0;
        BOOL is=YES;
        for (Mothy *mo in self.array) {
        if ([mo.picture isEqualToString:@"type_big_0"]) {
            
                int b=[mo.closed intValue];
                nu+=b;
                self.liftLable.text=[NSString stringWithFormat:@"%d",nu];
            is=NO;
        }
    }
            if (is==YES) {
        self.liftLable.text=@"0";
        }
       //删除Codata数据库的的某一类对象必须遍历
        NSFetchRequest *request=[[NSFetchRequest alloc]initWithEntityName:@"Mothy"];
        NSArray *array=[[CoreDataHandle shareCoreDataHandle].context executeFetchRequest:request error:nil];
        if (array.count>0) {
            for (Mothy *a in array) {
                if ([a.name isEqualToString:acodate.name]) {
                    [[CoreDataHandle shareCoreDataHandle].context deleteObject:a];
                }
            }
            if ([[CoreDataHandle shareCoreDataHandle].context hasChanges]) {
                [[CoreDataHandle shareCoreDataHandle].context save:nil];
            }
            
        }
        
       } ];
    UIAlertAction *acetion2=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:acetion2];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)editAction:(UIButton*)sender{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"name" object:nil];
 
    UIView *v = [sender superview];//获取父类view
    UICollectionViewCell *cell =(UICollectionViewCell*)[v superview];//获取cell
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];//获取cell对应的indexpath;
    ModifyViewController *modifyVC=[[ModifyViewController alloc]init];
    modifyVC.modle=self.array[indexPath.row];
    UINavigationController *modifyNC=[[UINavigationController alloc]initWithRootViewController:modifyVC];
    [self presentViewController:modifyNC animated:YES completion:nil];
}
-(void)tapGRAction:(UITapGestureRecognizer*)sender{
    CABasicAnimation *ba=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    //2.1设置持续时间
    ba.duration=1.0f;
    //2.2设置开始值
    ba.fromValue=@(0);
    //2.3设置结束值
    ba.toValue=@(M_PI);
   //3设置结束值
    [self.tapimageView.layer addAnimation:ba forKey:@"tapimageView"];
    //延迟2秒
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AccoutTextViewController *accoutVC=[[AccoutTextViewController alloc]init];
        UINavigationController *accoutNC=[[UINavigationController alloc]initWithRootViewController:accoutVC];
        [self presentViewController:accoutNC animated:YES completion:nil];
    });
}

-(void)dealloc{
    [self.tapimageView.layer removeAnimationForKey:@"tapimageView"];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    Mothy *moth=self.array[indexPath.row];
    
    if ([moth.picture isEqualToString:@"type_big_24"]) {
        //创建
        UINib *nib = [UINib nibWithNibName:@"AccountCollectionViewCell"
        bundle: [NSBundle mainBundle]];
        [collectionView registerNib:nib forCellWithReuseIdentifier:@"AccountCollectionViewCell"];
        AccountCollectionViewCell *cell = [[AccountCollectionViewCell alloc]init];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"AccountCollectionViewCell"forIndexPath:indexPath];

        [cell.deleteButton addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell setCellmodel:moth];
        return cell;
    }

        //创建
        UINib *nib = [UINib nibWithNibName:@"AcoutLiftCollectionViewCell"bundle: [NSBundle mainBundle]];
        [collectionView registerNib:nib forCellWithReuseIdentifier:@"AcoutLiftCollectionViewCell"];
       AcoutLiftCollectionViewCell  *cell = [[AcoutLiftCollectionViewCell alloc]init];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"AcoutLiftCollectionViewCell"forIndexPath:indexPath];
  
    [cell.deleteButton addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
     [cell.endButton addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell setCellDateForModel:moth];
    
       return cell;
}







#pragma mark----实现代理方法 UICollectionViewDelegate;
//是否可以点击
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return     UIEdgeInsetsMake(0, 10,0, 10);
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
   CGSize size=CGSizeMake([UIScreen mainScreen].bounds.size.width-15, 80);
    return size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
